package com.example.concurrentprogramming8016.thread;

/**
 * @author liyanhao
 * @Date 2023-01-04 2:22
 * 使用wait/notify阻塞唤醒线程
 * 1.只能在同步代码块中
 * 2.只能唤醒一个线程中的等待
 */
public class WaitTest {
    public void testWaitMethod(Object lock) throws InterruptedException {
        synchronized (lock) {
            System.out.println(Thread.currentThread().getName() + "begin wait()");
            //sleep睡眠不会释放锁资源
            Thread.sleep(5000);
            //wait 释放锁资源
            lock.wait();

            System.out.println(Thread.currentThread().getName() + "end wait");
        }
    }

    public void testNotifyMethod(Object lock) {
        synchronized (lock) {
            System.out.println(Thread.currentThread().getName() + " begin notify()");
            lock.notify();
            System.out.println(Thread.currentThread().getName() + " end notify");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Object lock = new Object();
        WaitTest waitTest = new WaitTest();

        new Thread(() -> {
            try {
                waitTest.testWaitMethod(lock);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "thread1").start();

        new Thread(()->{
            waitTest.testNotifyMethod(lock);
        },"thread2").start();


    }
}
